//
//  IsEqualOriginValueViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/24.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift

extension ObservableConvertibleType where E: Equatable {
     
    //将原始序列（当前值）转换成（当前值, 是否与最初值相同）的序列
    func isEqualOriginValue() -> Observable<(value: E, isEqualOriginValue: Bool)> {
        return self.asObservable()
            .scan(nil){ acum, x -> (origin: E, current: E)? in
                if let acum = acum {
                    return (origin: acum.origin, current: x)
                } else {
                    return (origin: x, current: x)
                }
            }
            .map { ($0!.current, isEqualOriginValue: $0!.origin == $0!.current) }
    }
}

class IsEqualOriginValueViewController: UIViewController {

    let disposeBag = DisposeBag()
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var switchx: UISwitch!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "59.检测当前值与初始值是否相同：isEqualOriginValue"
        view.backgroundColor = .white
        
        test()
        test2()
        test3()
    }

    func test() {
        Observable.of("a", "b", "c", "a", "e")
        .isEqualOriginValue()
        .subscribe(onNext: {
            print("当前值是：\($0.value)", "是否与除初始值相同：\($0.isEqualOriginValue)" )
        })
        .disposed(by: disposeBag)
    }
    
    func test2() {
        //创建文本输入框
        textField.text = "hangge"  //初始值设为：hangge
        textField.borderStyle = UITextBorderStyle.roundedRect
         
        //当文本框内容改变时，将内容输出到控制台上
        textField.rx.text.orEmpty.asObservable()
            .isEqualOriginValue()
            .subscribe(onNext: {
                print("当前值是：\($0.value)", "是否与除初始值相同：\($0.isEqualOriginValue)" )
            })
            .disposed(by: disposeBag)
    }
    
    func test3() {
        switchx.isOn = true //设置默认值
         
        //当开关状态改变时，将内容输出到控制台上
        switchx.rx.isOn.asObservable()
            .isEqualOriginValue()
            .subscribe(onNext: {
                print("当前值是：\($0.value)", "是否与除初始值相同：\($0.isEqualOriginValue)" )
            })
            .disposed(by: disposeBag)
    }
}
